import {onMounted, Ref, ref} from "vue";
import {UserInfoType} from "../common/Type/UserInfoType";
import {useUserStore} from "../store/user"
import route from "../route";

/**
 * 用户信息的hook
 */
export default function () {
  // 用户信息状态
  let userStore = useUserStore()
  // 用户信息
  const userinfo: Ref<UserInfoType> = ref<UserInfoType>({} as UserInfoType)

  /**
   * 设置用户信息
   * @param userinfovalue 用户信息
   */
  const setUserInfo = (userinfovalue: UserInfoType): void => {
    if (userinfo) {
      localStorage.setItem("userinfo", JSON.stringify(userinfovalue))
      localStorage.setItem("token", userinfovalue.token)
      userStore.userInfo = JSON.stringify(userinfovalue)
      userinfo.value = userinfovalue
      route.push({name: 'index'})
    }
  }

  /**
   * 退出登录
   */
  const logOut = (): void => {
    localStorage.removeItem("userinfo")
    localStorage.removeItem("token")
    userStore.userInfo = ""
    userinfo.value = {} as UserInfoType
    route.push({name: 'login'})
  }

  /**
   * 获取用户token
   */
  const getToken = (): string => {
    return userinfo.value.token
  }

  onMounted(() => {
    if (userStore.userInfo) {
      userinfo.value = JSON.parse(userStore.userInfo)
    }
  })
  return {
    userinfo,
    setUserInfo,
    logOut,
    getToken
  }
}
